﻿using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Drawing;

namespace Infragistics.Web.Mvc
{
    [ToolboxData("<{0}:IGMvcScriptManager ID=\"IGMvcScriptManager\" runat=\"server\" />")]
    [ToolboxBitmap(@"C:\Users\cshoemaker.INFRAGISTICS\Projects\IGFiles\trunk\IGMVC\src\Infragistics.Web.Mvc\IGMvcScriptManager.bmp")]
    public class IGMvcScriptManager : Control
    {
        private ScriptManager scriptManager = null;
        private HtmlForm htmlForm = new HtmlForm();

        protected override void OnInit(EventArgs e)
        {
            scriptManager = ScriptManager.GetCurrent(this.Page);

            if (ScriptManager.GetCurrent(this.Page) == null)
            {
                scriptManager = new ScriptManager();
                scriptManager.ID = "igMvcScriptManager";
                scriptManager.EnablePartialRendering = true;
                this.Controls.Add(htmlForm);
                htmlForm.Controls.Add(scriptManager);
            }

            base.OnInit(e);
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            //base.RenderControl(writer);

            if (!DesignMode)
            {
                Hashtable ht = new Hashtable();

                foreach (RegisteredScript rs in scriptManager.GetRegisteredClientScriptBlocks())
                {
                    if (!ht.ContainsKey(rs.Key))
                    {
                        this.Page.Response.Write("<script src=\"" + rs.Url + "\"></script>" + Environment.NewLine);
                        ht.Add(rs.Key, rs.Key);
                    }
                }

                this.Page.Response.Write("<script type=\"text/javascript\">var theForm=new Object();" +
                        "theForm.action=\"\";" +
                        "if (!(typeof($IG) === 'undefined')) $IG.ControlCallbackManager.prototype._getForm=function(){return document;}</script>" + Environment.NewLine);

                this.Page.Response.Write("<script type=\"text/javascript\">Sys.Application.initialize();</script>");

                foreach (RegisteredScript rs in scriptManager.GetRegisteredStartupScripts())
                {
                    if (rs.Script.Trim().StartsWith("<script"))
                    {
                        this.Page.Response.Write(rs.Script);
                        if (!rs.Script.Trim().EndsWith("</script>"))
                            this.Page.Response.Write(" </script>");
                    }
                    else
                    {
                        this.Page.Response.Write("<script type=\"text/javascript\">");
                        this.Page.Response.Write(rs.Script);
                        this.Page.Response.Write(" </script>");
                    }
                }

            }
        }
    }
}